package scan.config;

import org.apache.shardingsphere.api.config.masterslave.MasterSlaveRuleConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.MasterSlaveDataSourceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Configuration
public class ShardingJdbcConfig {
    @Autowired
    private DataSource firstDataSource;

    @Autowired
    private DataSource secondDataSource;

    @Bean
    @Primary
    public DataSource getDataSource() throws SQLException {
        return buildDataSource();
    }


    private DataSource buildDataSource() throws SQLException {
        //设置从库数据源集合
        Map<String, DataSource> dataSourceMap = new HashMap<>();
        dataSourceMap.put("write", firstDataSource);
        dataSourceMap.put("read", secondDataSource);

        // 配置读写分离规则
        MasterSlaveRuleConfiguration masterSlaveRuleConfig = new MasterSlaveRuleConfiguration("ds_write_read",
                "write", Collections.singletonList("read"));

        //根据ShardingPropertiesConstant设置debugger的一些信息
        Properties properties = new Properties();
        properties.setProperty("sql.show", String.valueOf(true));
        // 获取数据源对象
        DataSource dataSource = MasterSlaveDataSourceFactory.createDataSource(dataSourceMap, masterSlaveRuleConfig,properties );
        return dataSource;
    }



}
